<template>
  <div class="org">
    <el-row>
      <el-col :xs="24" :lg="8">
        <el-card class="box-card left">
          <el-tree
            :data="tree.data"
            ref="tree"
            node-key="key"
            :default-expanded-keys="['custom' + USER.user.rentId]"
            @node-click="treeClick"
            accordion
            :render-content="treeContent">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="16">
        <el-card class="box-card right">
          <div slot="header" class="clearfix">
            <span style="line-height: 36px;"> {{tree.select.name || '组织'}} 详情</span>
            <el-button style="float: right;" type="primary" v-if="tree.select.id !== 0" @click="dialogOpen('PUT')">修改</el-button>
          </div>
          <el-form labelWidth="80px" label-position="left" v-if="tree.select.id !== 0">
            <el-row>
              <el-col :xs="24" :lg="{span: 10, offset: 0}">
                <el-form-item label="组织名">
                  <el-tag type="success">{{tree.select.name}}</el-tag>
                </el-form-item>
                <el-form-item label="负责人">
                  <span>{{tree.select.master}}</span>
                </el-form-item>
                <el-form-item label="所属客户">
                  <span>{{tree.select.show_rentId}}</span>
                </el-form-item>
                <el-form-item label="创建时间">
                  <span>{{formatterTime(tree.select.createtime, 1)}}</span>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 10, offset: 2}">
                <el-form-item label="组织编码">
                  <span>{{tree.select.oCode}}</span>
                </el-form-item>
                <el-form-item label="上级组织">
                  <span>{{tree.select.parent}}</span>
                </el-form-item>
                <el-form-item label="备注">
                  <span>{{tree.select.remark}}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <p v-if="tree.select.id === 0">点击组织树，查看详情</p>
        </el-card>
      </el-col>
    </el-row>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}<span>{{formDialog.id ? ('组织编码：' + formDialog.oCode) : ''}}</span></p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="rentid" label="所属客户">
              <el-tag type="success">{{formDialog.rent}}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="parent" label="上级组织">
              <el-tag type="success">{{formDialog.parent||'顶级组织'}}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="name" label="组织名">
              <el-input type="text"
                        v-model="formDialog.name"
                        placeholder="机构名" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="oCode"
                          v-if="!formDialog.id"
                          label="组织编码">
              <el-input type="text"
                        v-model="formDialog.oCode"
                        placeholder="组织编码" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="master" label="负责人">
              <el-input type="text"
                        v-model="formDialog.master"
                        placeholder="组织负责人" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="remark" label="备注">
              <el-input type="textarea"
                        :autosize="{ minRows: 1, maxRows: 2}"
                        v-model="formDialog.remark"
                        placeholder="备注" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="createTime" prop="createtime" label="创建时间">
          {{formDialog.createtime?formatterTime(formDialog.createtime, 1):formatterTime(new Date(), 1)}}
        </el-form-item>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {get} from '~/plugins/axios';
  import {AutoVue, AutoPromise} from '~/plugins/Tools';
  /**
   * 模板思想
   */
  function __form () {
    return {
      'id': { // 机构ID 前端填充
        value: 0,
      },
      'createtime': { // 创建时间 后台生成
        value: '',
      },
      'master': { // 组织负责人 必填
        value: '',
        rule: ['vNull'],
      },
      'name': { // 机构名 必填
        value: '',
        rule: ['vNull'],
      },
      'parentid': { // 父 ID 前端填充
        value: 0,
        rule: ['vNull'],
      },
      'remark': { // 备注 非必填
        value: '',
      },
      'oCode': { // 组织编码 必填
        value: '',
        rule: ['vNull'],
      },
      'rentid': { // 所属客户 ID
        value: 1,
      },
      parent: '',
      rent: '',
    };
    /**
     *
     * parent 当点击 任意节点 的时候 获取 父id 对应的 label
     *
     *
     */
  }
  export default AutoVue({
    name: 'org-safety',
    transition: 'slide-fade',
    data: {
      tree: {
        data: [],
        select: {
          'id': 0,
          'createtime': 0,
          'master': '',
          'name': '',
          'parentid': 0,
          'remark': '',
          'oCode': 0,
          'rent': {
            'id': 0,
            'address': '0',
            'createtime': 0,
            'descr': '0',
            'name': '0',
            'netstation': '0',
            'scale': 0,
            'trades': '0',
            'type': 0,
          },
        },
      },
      dialog: {
        title: '新增',
        saveParameter: {},
      },
      formDialog: __form(),
    },
    store: ['CUSTOM_customers', 'USER', 'ORG_org'],
    methods: {
      treeContent (h, { node, data, store }) {
        let _this = this;
        return (
          <span>
            <span>
              <span>{node.label}</span>
            </span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="primary" icon="plus" class={{'display': _this.USER.auth.indexOf('addOrg') === -1}} on-click={ event => this.treeAppend(event, store, data) }></el-button>
              <el-button size="mini" type="danger" icon="delete" class={{ 'display': (node.childNodes.length !== 0 || node.level === 1 || _this.USER.auth.indexOf('deleteOrg') === -1) }} on-click={ event => this.treeRemove(event, store, data) }></el-button>
            </span>
          </span>);
      },
      async treeClick (data, node, tree) {
        if (node.level === 1) return;
        if (!data.detail) {
          data.detail = await this.get('/org/getOrgInfo/' + data.key);
          if (data.detail.parentid === '0') {
            data.detail.parent = '顶级组织';
          } else {
            data.detail.parent = node.parent.data.label;
          }
        }
        this.tree.select = Object.assign(data.detail, {rent: data.rent});
      },
      treeAppend (event, store, data) {
        this.dialogOpen('ADD', {store, data});
        event.stopPropagation();
      },
      treeRemove (event, store, data) {
        this.$confirm('您将删除本节点。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/org/delete/', [data.key]);
              store.remove(data);
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {});
        event.stopPropagation();
      },
      dialogInit () {
        this.formDialog = {
          ...this.formDialog,
          ...this.ObjectClone(__form()),
        };
        this.resetFields('formDialog');
      },
      dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        }
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.dialog.saveParameter = more;
          let {data} = more;
          if (data.level) {
            this.formDialog.parentid = 0;
            this.formDialog.parent = '顶级组织';
          } else {
            this.formDialog.parentid = parseInt(data.key);
            this.formDialog.parent = data.label;
          }
          this.formDialog.id = 0;
          this.formDialog.rentid = data.rentid;
          this.formDialog.rent = data.rent;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          for (let index in __form()) {
            this.formDialog[index] = this.tree.select[index];
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        let more = this.dialog.saveParameter;
        if (this.dialog.title === '新增') {
          this.VALIDATE('formDialog', async option => {
            option.createtime = (new Date()).getTime();
            let parent = option.parent;
            let rent = option.rent;
            let parentid = option.parentid;
            let rentid = option.rentid;
            delete option.parent;
            delete option.rent;
            try {
              let json = await this.post('/org/add', option);
              let {store, data} = more;
              store.append({
                parent,
                rent,
                parentid,
                rentid,
                key: json.id,
                label: option.name,
                children: [],
              }, data);
              this.dialogInit();
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE('formDialog', async option => {
            let rent = option.rent;
            delete option.parent;
            delete option.rent;
            try {
              await this.post('/org/add', option);
              for (let index in this.tree.select) {
                if (this.tree.select.hasOwnProperty(index)) {
                  this.tree.select[index] = option[index];
                }
              }
              this.tree.select.parent = rent;
              this.$refs.tree.store.nodesMap[option.id + ''].data.label = option.name;
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
      findCustom (customid) {
        for (let item of this.CUSTOM_customers) {
          if (customid === item.id) return item.name;
        }
      },
    },
    async mounted () {
      if (this.tree.data.length !== 0) return;
      let store = this.$store;
      await AutoPromise([
        async () => {
          if (store.state.ORG.org.length === 0) {
            let data = await get('/org/' + store.state.USER.user.rentId);
            store.commit('ORG/SET', data);
          }
        },
        async () => {
          if (store.state.CUSTOM.customers.length === 0) {
            let data = await get('/custom/');
            store.commit('CUSTOM/SET', data);
          }
        },
      ]);
      let org = Object.assign(this.ORG_org);
      for (let item of org) {
        let customid = parseInt(item.key.substring(6));
        let custom = this.findCustom(customid);
        item = autoAddCustomId(item, customid, custom);
        item.level = 1;
        this.tree.data.push(Object.assign({}, item));
      }
    },
  });
  function autoAddCustomId (obj, customid, custom) {
    obj.rentid = customid;
    obj.rent = custom;
    if (obj.children.length === 0) return obj;
    for (let item of obj.children) {
      item = autoAddCustomId(item, customid, custom);
    }
    return obj;
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }
  .el-tag{
    font-size: 14px;
  }
  .createTime{
    margin-bottom: -20px;
    z-index: -1;
    position: relative;
  }
  @media screen and (max-width: 800px) {
    .box-card {
      margin: 0;
    }
    .left{
      border: none;
      border-radius: 0;
      overflow: auto;
      box-shadow: none;
    }
    .createTime{
      margin-bottom: -45px;
    }
  }
</style>

<style lang="scss">
  .org{
    .el-tree-node__content{
      .el-button{
        /*display: none;*/
      }
    }
    .right{
      .el-card__body{
        padding:20px;
      }
    }
  }
</style>
